package com.example.bookshelf.data

import com.alibaba.fastjson2.JSONObject
import com.example.bookshelf.network.Book
import com.example.bookshelf.network.BookApiService

interface BookShelfRepository {
    suspend fun getBooks(bookType: String): List<Book>
}

class NetworkBookShelfRepository(private val bookApiService: BookApiService) : BookShelfRepository {
    override suspend fun getBooks(bookType: String): List<Book> {
        val books = mutableListOf<Book>()

        val result = bookApiService.getBooks(bookType)
        val json = JSONObject.parseObject(result)
        val items = json.getJSONArray("items")
        val size = items.size.coerceAtMost(30)
        for (i in 0 until size) {
            val item = items.getJSONObject(i)
            val volumeInfo = item.getJSONObject("volumeInfo")
            val id = item.getString("id")
            val title = volumeInfo.getString("title")

            val details = bookApiService.getBook(id)
            val detailsJson = JSONObject.parseObject(details)
            val imageLinks = detailsJson.getJSONObject("volumeInfo").getJSONObject("imageLinks")
            val imgUrl = imageLinks.getString("small") ?: imageLinks.getString("thumbnail")

            books.add(Book(id, title, imgUrl.replace("http:", "https:")))
        }
        return books
    }
}
